package com.secondmybatis.contorller;

import com.secondmybatis.entity.Result;
import com.secondmybatis.utils.AliyunOSSUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

//@Slf4j
@RestController
public class UploadController {

//    /**
//     * 文件上传->本地存储
//     * @param username
//     * @param age
//     * @param file
//     * @return
//     */
//    @PostMapping("/upload")
//    public Result upload(String username, Integer age, MultipartFile file) throws Exception {
////        log.info("{},{},{}",username,age,file);
//        // 1.获取原始文件名,取出.jpg 或 .png
//        String originalFilename = file.getOriginalFilename();
//        // 2.通过UUID生成随机字符
//        String newFileName = UUID.randomUUID()+originalFilename.substring(originalFilename.lastIndexOf("."));
//        // 3.需要将前端上传的文件存到本地
//        file.transferTo(new File("D:/"+newFileName));
//        return Result.success(newFileName);
//    }

//    private final String bucketName = "secondmybatis";
//    private final String endpoint = "https://oss-cn-shenzhen.aliyuncs.com";
//    private final String region = "cn-shenzhen";

    //    改造参数代码
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.region}")
    private String region;

    /**
     * 文件上传->阿里云OSS存储
     *
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws Exception {
//        log.info("{},{},{}",username,age,file);
        // 1.获取原始文件名,取出.jpg 或 .png
        String originalFilename = file.getOriginalFilename();
        System.out.println("原始文件名：" + originalFilename);
        String extName = originalFilename.substring(originalFilename.lastIndexOf(".")); // 获取后缀
        // 2.调用阿里云OSS工具类，将文件上传到OSS
        String url = AliyunOSSUtils.upload(endpoint, bucketName, region, file.getBytes(), extName);
        System.out.println("阿里云返回的url:"+url);
        return Result.success(url);
    }
}
